﻿using Nemerle.Collections;
using Nemerle.Text;
using Nemerle.Utility;
using Nemerle.Compiler;

using System;
using System.IO;
using System.Reflection;
using System.Collections.Generic;
using System.Linq;

namespace NPad
{
  /// <summary>
  /// Description of Compiler.
  /// </summary>
  public class ManagedCompiler: ICompiler
  {
      mutable nemerlePath : string;
      
      public Compile(fileName : FileInfo, log : TextWriter) : Assembly
      {
        def options = CompilationOptions();
        def manager = ManagerClass(options);
        
        manager.InitOutput(System.IO.TextWriter.Null);
        manager.MessageOccured += (_, msg) => log.WriteLine(msg);
        
        try
        {
          when (!String.IsNullOrEmpty(nemerlePath))
            options.LibraryPaths ::= nemerlePath;
          
          options.IgnoreConfusion = true;
          options.ProgressBar = false;
          options.Sources = [fileName.FullName];
          options.CompileToMemory = true;
          options.ColorMessages = false;
          
          manager.Run();
          manager.GeneratedAssembly
        }
        catch
        {
          | _ is Recovery => null
        }
      }
      
      public SetNemerlePath(path : string) : void
      {
      	nemerlePath = path;
      }
  }
}
